<?php

namespace StudyBuddy\Api\v1;

use \StudyBuddy\Api\Api;
use \StudyBuddy\AnswerParser;
use \StudyBuddy\String\HTMLString;
use \StudyBuddy\Question;

/**
 * Controller for adding new Answer via
 * API POST
 *
 */
class Addanswer extends Api {

    protected $permission = 'answer';
    protected $bRequirePost = true;
    protected $membersOnly = true;

    /**
     * Submitted Answer object
     *
     * @var object of type SubmittedAnswer
     */
    protected $oSubmitted;
    protected $aRequired = array('qbody', 'qid');

    /**
     * Object of newly created Answer
     *
     * @var object of type \StudyBuddy\Answer
     */
    protected $oAnswer;

    /**
     * Question object represents the
     * question for which this answer is being parsed
     *
     *
     * @var object of type \StudyBuddy\Question
     */
    protected $oQuestion;

    protected function main() {
        $this->oSubmitted = new SubmittedAnswer($this->oRegistry);

        $this->getQuestion()
                ->validateBody()
                ->process()
                ->setOutput();
    }

    /**
     * Get data for Question based on qid Request param
     *
     * @throws \StudyBuddy\HttpResponseCodeException in case
     * Question with passed "qid" is not found OR if it is
     * marked as deleted
     *
     * @return object $this
     */
    protected function getQuestion() {

        $aQuestion = $this->oRegistry->Mongo->QUESTIONS->findOne(array('_id' => (int) $this->oRequest['qid']));

        /**
         * @todo Translate string
         */
        if (empty($aQuestion)) {
            throw new \StudyBuddy\HttpResponseCodeException('Question not found', 404);
        }

        if (!empty($aQuestion['i_del_ts'])) {

            throw new \StudyBuddy\HttpResponseCodeException('This question was deleted on ' . date('r', $aQuestion['i_del_ts']), 404);
        }

        $this->oQuestion = new Question($this->oRegistry, $aQuestion);


        return $this;
    }

    /**
     * Validate minimum length and min required
     * word count of body
     *
     * @throws \StudyBuddy\HttpResponseCodeException
     *
     * @return object $this
     */
    protected function validateBody() {
        $minChars = $this->oRegistry->Ini->MIN_ANSWER_CHARS;
        $minWords = $this->oRegistry->Ini->MIN_ANSWER_WORDS;
        $body = $this->oSubmitted->getBody();
        $oHtmlString = HTMLString::factory($body);
        $wordCount = $oHtmlString->getWordsCount();
        $len = $oHtmlString->length();

        if ($len < $minChars) {
            throw new \StudyBuddy\HttpResponseCodeException('Answer must contain at least ' . $minChars . ' letters', 400);
        }

        if ($wordCount < $minWords) {
            throw new \StudyBuddy\HttpResponseCodeException('Answer must contain at least ' . $minWords . ' words', 400);
        }

        return $this;
    }

    /**
     * Process submitted Answer using AnswerParser class
     *
     * @throws \StudyBuddy\HttpResponseCodeException
     */
    protected function process() {
        $oAdapter = new AnswerParser($this->oRegistry);
        try {
            $this->oAnswer = $oAdapter->parse($this->oSubmitted);
            d('cp created new answer ' . $this->oAnswer->getResourceId());
        } catch (\StudyBuddy\QuestionParserException $e) {
            $err = $e->getMessage();
            d('$err: ' . $err);

            throw new \StudyBuddy\HttpResponseCodeException('Unable to add this answer: ' . $err, 400);
        }

        return $this;
    }

    /**
     * Entire Answer data will be returned
     * in request
     *
     * @return object $this
     */
    protected function setOutput() {

        /* $d = __METHOD__.' '.__LINE__;
          exit($d); */

        $a = $this->oAnswer->getArrayCopy();
        /**
         * @todo maybe use special template
         * for 'app' instead of default template?
         *
         */
        $a['edit_delete'] = ' <span class="ico del ajax" title="Delete">delete</span>  <span class="ico edit ajax" title="Edit">edit</span>';
        $a ['html'] = \tplAnswer::parse($a);
        d('before sending out $a: ' . print_r($a, 1));

        $this->oOutput->setData($a);

        return $this;
    }

}
